﻿using System.Windows;
using System.ComponentModel;
using Results.ViewModels;

namespace Results.Views
{
    public partial class MainView
    {
        /// <summary>
        /// The code behind in this file is to deal with binding the visual state manager with MainViewModel.Show
        /// </summary>
        public MainView()
        {
            InitializeComponent();
            Loaded += MainPageLoaded;
        }

        /// <summary>
        /// This is called after the data context (the main viewmodel) is assigned
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void MainPageLoaded(object sender, RoutedEventArgs e)
        {
            var mainViewModel = DataContext as MainViewModel;
            if (mainViewModel != null)
            {
                // request property changes from the main viewmodel
                mainViewModel.PropertyChanged += MainViewModelPropertyChanged;

                // prime the view state
                MainViewModelPropertyChanged(mainViewModel, new PropertyChangedEventArgs("Show"));
            }
        }

        /// <summary>
        /// This is called whenever any property (including Show) changes in the main viewmodel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void MainViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            var mainViewModel = sender as MainViewModel;
            if (mainViewModel != null)
            {
                if (e.PropertyName == "Show")
                {
                    // adjust the layout to show what the viewmodel dictates should be shown
                    VisualStateManager.GoToState(this, mainViewModel.Show.ToString(), true);

                    // once a specific player or tournament is shown...
                    // ...make the respective button visible for the remaining duration of the application
                    if (mainViewModel.Show == MainViewModel.ShowOptions.Player)
                    {
                        selectedPlayerButton.Visibility = Visibility.Visible;
                    }
                    if (mainViewModel.Show == MainViewModel.ShowOptions.Tournament)
                    {
                        selectedTournamentButton.Visibility = Visibility.Visible;
                    }
                }
            }
        }
    }
}
